<template>
    <div class="home" v-loading="loading">
        <div class="home-btn">
           <el-button :disabled="list?.length === 5"  class="srt-el-button srt-el-button--primary srt-el-button-h32 btn" type="primary" @click="handleUpdate">添加作业</el-button>
        </div>
         <ul class="home-list" v-if="list.length">
            <li v-for="(item, index) in list" :key="item.homeWorkId">
                <div class="top">
                    <div class="name">{{item.name}}</div>
                    <el-popover v-if="item.context"
                        placement="top-start"
                        :show-arrow="false"
                        width="400px"
                        trigger="hover"
                        :content="item.context"
                    >
                        <template #reference>
                           <div class="desc">{{ item.context || '暂无描述' }}</div>
                        </template>
                    </el-popover>
                    <div v-else class="desc">{{ item.context || '暂无描述' }}</div>
                </div>
                <div class="bottom">
                    <div class="home-file-item">
                        <span class="label">作业附件：</span>
                        <div class="home-file" v-if="item.homeworkMaterialList?.length">
                            <FileItem v-for="fileItem in item.homeworkMaterialList" :key="fileItem.materialId" :fileData="fileItem.materialVo" showOp showPreview></FileItem>
                        </div>
                        <span v-else>暂无附件</span>
                    </div>
                    <div v-if="item.times > 0"><span class="label">作业要求：</span><span>有效提交次数为{{item.times}}次</span></div>
                    <div><span class="label">是否必做：</span><span>{{item.compulsory == 1 ? '是' : '否'}}</span></div>
                </div>
                <div class="operate">
                    <i class="iconfont icon-muke-paixu-shang" v-if="index > 0 && list.length > 1" @click="move(index, 'top')"></i>
                    <i class="iconfont icon-muke-paixu-xia" v-if="index < list.length - 1 && list.length > 1" @click="move(index, 'bottom')"></i>
                    <i class="iconfont icon-bianji" @click="handleUpdate(item)"></i>
                    <i class="iconfont icon-shanchu" @click="handleDelete(item, index)"></i>
                </div>
            </li>
         </ul>
         <NoData v-else url="no-course.png" info="还没有添加作业"></NoData>
    </div>
    <PublishHomeworkDialog v-model="showDialog" :form="homeData" :list="list" @refresh="updateList"/>
</template>

<script setup>
import FileItem from './dialog/file-item.vue';
import NoData from '@/components/no-data.vue';
import PublishHomeworkDialog from './dialog/publish-homework-dialog.vue';
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { deepCopy } from '@/lib/tools.js';
import Confirm from '@/components/confirm/confirm.js'

const emit = defineEmits(['update-detail']);

const route = useRoute();

const props = defineProps({
    detail: {
        type: Object,
        default: () => {
            return {};
        }
    }
})

const list = ref([]);

const showDialog = ref(false);

const homeData = ref({});

function handleUpdate(data = {}) {
    if (!(props.detail.state === 1 || props.detail.state === 3)) {
        let message = props.detail.publishState === 1 && props.detail.state === 4 ? '该慕课已发布，请取消发布后再操作' : '该慕课正在审核中，无法操作';
        G_dispatchEvent('toast', { message, type: 'error' })
        return;
    }
    showDialog.value = true;
    homeData.value = deepCopy(data);
}

// 更新作业列表
function updateList() {
    getList();
}

const loading = ref(false);

function getList() {
    loading.value = true;
    G_transmit('homeworkList', {
        queries: {
            moocId: route.params.moocId,
        }
    })
    .then((res) => {
        let homeList = res.data || [];
        homeList.sort((a, b) => {
			return a.sort - b.sort;
		})
        list.value = homeList.map(item => {
             item.materialIdList = item.homeworkMaterialList?.length && item.homeworkMaterialList.map(file => file.materialId) || [];
             return item;
        });
    })
    .catch((_err) => {
        console.log(_err)
    }).finally(() => {
        loading.value = false;
    });
}

function move(index, type) {
    if (!(props.detail.state === 1 || props.detail.state === 3)) {
        let message = props.detail.publishState === 1 && props.detail.state === 4 ? '该慕课已发布，请取消发布后再操作' : '该慕课正在审核中，无法操作';
        G_dispatchEvent('toast', { message, type: 'error' })
        return;
    }
    if(type === 'top') {
        [list.value[index - 1], list.value[index]] = [list.value[index], list.value[index - 1]];
    }else {
        [list.value[index], list.value[index + 1]] = [list.value[index + 1], list.value[index]];
    }
    let arr = list.value?.length && list.value.map((item, index) => {
         item.sort = index + 1;
         return item;
    }) || [];
    confirmSave(arr, []);
}

// 保存
function confirmSave (homeWorkInsertInfoRequestList = [], homeworkIdList = []) {
    G_transmit('homeworkAdd', {
        data: {
            homeWorkInsertInfoRequestList,
            homeworkIdList,
            moocId: route.params.moocId,
        }
    }).then((res) => {
        let tip = homeworkIdList.length ? '删除成功' : '移动成功';
        G_dispatchEvent('toast', { message: tip, type: 'success'});
        getList();
    }).catch((_err) => {
        console.log(_err)
    })
}

function handleDelete(item, index) {
    if (!(props.detail.state === 1 || props.detail.state === 3)) {
        let message = props.detail.publishState === 1 && props.detail.state === 4 ? '该慕课已发布，请取消发布后再操作' : '该慕课正在审核中，无法操作';
        G_dispatchEvent('toast', { message, type: 'error' })
        return;
    }
    Confirm(
        { 
            title: '温馨提示', 
            text: '确认要删除该作业吗？'
        }
    )
    .then(ret => {
        confirmDelete(item, index);
    })
    .catch(_err => {
        console.log(_err);
    }) 
   
}

function confirmDelete(item, index) {
    let listArr = deepCopy(list.value);
    listArr.slice(index, 1);
    let arr = listArr?.length && listArr.map((item, index) => {
         item.sort = index + 1;
         return item;
    }) || [];
    confirmSave(arr, [item.homeWorkId]);
}

onMounted(() => {
    getList();
})

</script>

<style lang="scss" scoped>
.home-list {
    padding-bottom: 20px;
    li {
        border-radius: 4px;
        border: 1px solid #E0E2E4;
        padding: 20px 20px 4px;
        position: relative;
        font-size: 14px;
        margin-bottom: 20px;
        transition: all 0.2s;
    }
    .top {
        padding-bottom: 16px;
        border-bottom: 1px solid #E0E2E4;
    }
    .name {
        color: var(--srt-main-text-color);
        font-weight: bold;
    }
    .desc {
        color: var(--srt-main-text-color);
        line-height: 21px;
        margin-top: 9px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
    }

    .bottom {
        padding-top: 16px;
        &>div {
           margin-bottom: 16px;
        }
        .label {
            color: var(--srt-color-gray);
           
        }
    }
    .operate {
        position: absolute;
        right: 20px;
        bottom: 20px;
        .iconfont {
            margin-left: 12px;
            cursor: pointer;
            color: var(--srt-color-gray);
            &:hover {
                color: var(--srt-main-active-text-color);
            }
        }
    }
}

.home-btn {
    text-align: right;
    padding: 20px 0px;
    .btn {
        padding-left: 14px;
        padding-right: 14px;
    }
}

.home-file-item {
    display: flex;
    align-items: center;
    .home-file {
        width: 450px;
    }
}

</style>